class SetupController < ApplicationController
  before_filter :login_required
  protect_from_forgery :only => []
  
  def authorized?(user = current_player())
    return user.admin?
  end
  
  def export
  end

  def import
  end

  def new_world
  end

  def create_world
    cultures = params[:cultures].split(',') unless params[:cultures].nil?
    christian_names = params[:christian_names].split(',') unless params[:christian_names].nil?
    family_names = params[:family_names].split(',') unless params[:family_names].nil?
    kingdoms = params[:kingdoms].split(',') unless params[:kingdoms].nil?
    duchies = params[:duchies].split(',') unless params[:duchies].nil?
    counties = params[:counties].split(',') unless params[:counties].nil?
    towns = params[:towns].split(',') unless params[:towns].nil?
    
    @created = Array.new
    
    if cultures
      cultures.each do |str|
        @created = @created << Culture.find_or_create_by_name(str)
      end
    end
    
    if christian_names
      christian_names.each do |str|
        arr = str.split(":")
        culture = Culture.find_by_name(arr[1].strip)
        prev_name = culture.christian_names ? (culture.christian_names + ",") : ""
        culture.christian_names = prev_name + arr[0].strip
        culture.save
      end
    end
    
    if family_names
      family_names.each do |str|
        arr = str.split(":")
        culture = Culture.find_by_name(arr[1].strip)
        prev_name = culture.family_names ? (culture.family_names + ",") : ""
        culture.family_names = prev_name + arr[0].strip
        culture.save
      end
    end
    
    if kingdoms
      kingdoms.each do |str|
        arr = str.split(":")
        name = nil
        culture_name = nil
        if arr
          name = arr[0]
          culture_name = arr[1]
        else
          name = str
        end
        culture = nil
        if culture_name
          culture = Culture.find_or_create_by_name(culture_name.strip)
        end
        kingdom = Kingdom.find_or_create_by_name(name.strip)
        if culture
          kingdom.culture_id = culture.id
          kingdom.save
        end
        @created = @created << kingdom
      end
    end
    
    if duchies
      duchies.each do |str|
        arr = str.split(":")
        name = nil
        kingdom_name = nil
        if arr
          name = arr[0]
          kingdom_name = arr[1]
        else
          name = str
        end
        kingdom = nil
        if kingdom_name
          kingdom = Kingdom.find_or_create_by_name(kingdom_name.strip)
        end
        duchy = Duchy.find_or_create_by_name(name.strip)
        if kingdom
          duchy.kingdom_id = kingdom.id
          duchy.save
        end
        @created = @created << duchy
      end
    end
    
    if counties
      counties.each do |str|
        arr = str.split(":")
        name = nil
        duchy_name = nil
        if arr
          name = arr[0]
          duchy_name = arr[1]
        else
          name = str
        end
        duchy = nil
        if duchy_name
          duchy = Duchy.find_or_create_by_name(duchy_name.strip)
        end
        county = County.find_or_create_by_name(name.strip)
        if duchy
          county.duchy_id = duchy.id
          county.save
        end
        @created = @created << county
      end
    end
    
    if towns
      towns.each do |str|
        arr = str.split(":")
        name = nil
        county_name = nil
        if arr
          name = arr[0]
          county_name = arr[1]
        else
          name = str
        end
        county = nil
        if county_name
          county = County.find_or_create_by_name(county_name.strip)
        end
        town = Town.find_or_create_by_name(name.strip)
        if county
          town.county_id = county.id
          town.save
        end
        @created = @created << town
      end
    end
  end

  def populate_world
    config = GameConfig.singleton
    config.current_date = (36500) # 1100 AD
    config.save
    
    @populated = Array.new
    
    populate_kingdoms
    
    populate_duchies
    
    populate_counties
    
    populate_towns
    
    # Add a Pope
    pope = create_adult Kingdom.random, "male", "Ecclesiastical"
    Title.make_pope pope
    # Select a King to be Emperor
    king = Title.king_of Kingdom.random
    Title.make_emperor king
    
    give_children
    
    give_spouses
  end

  protected
  def child_age(mother)
      age = 0
      children = mother.children
      if children && children.size > 0
        oldest = children[0].age
        age = oldest - (rand(3) + 1)
        if age < 0
          age = 0
        end
      else
        age = mother.age - 16 unless mother.age < 16
      end
      return age
  end
  
  def create_child (father, age = child_age(father.partner))
      child = Character.born(father, father.partner, (rand(10) < 5 ? "male" : "female"), age)
      CharacterTrait.random_traits child
      @populated = @populated << child
      Relation.vassalize child, father
      return child
  end
  
  def create_adult (kingdom = Kingdom.random, sex = (rand(10) > 1 ? "male" : "female"), education = nil, culture = kingdom.culture)
      raise "Invalid culture" unless culture
      adult = Character.born(nil, nil, sex, age = (rand(50) + 16), culture, culture.generate_family_name)
      raise "Adult not created" unless adult
      CharacterTrait.random_traits adult, education
      @populated = @populated << adult
      return adult
  end
  
  def create_spouse(adult, kingdom = Kingdom.random)
    spouse = create_adult kingdom, adult.male? ? "female" : "male"
    adult.marry spouse
    return spouse
  end
  
  def create_court_officials (ruler, kingdom = Kingdom.random)
    official_number = 2 # skip admiral
    while official_number <= Title.court.size do
      official = create_adult kingdom, "male"
      Title.grant_title official, 3, official_number
      Relation.vassalize official, ruler
      official_number += 1
    end
  end
  
  def populate_kingdoms
    kingdoms = Kingdom.find(:all)
    if kingdoms
      kingdoms.each do |kingdom|
        # create king / queen
        ruler = create_adult kingdom, "male"
        Title.make_king ruler, kingdom
        # create spouse for ruler
        create_spouse ruler
        # create court officials
        create_court_officials ruler, kingdom
        # create cardinal
        priest = create_adult kingdom, "male", "Ecclesiastical"
        Title.make_cardinal priest, kingdom
        Relation.vassalize priest, ruler
      end
    end
  end
  
  def populate_duchies
    duchies = Duchy.find(:all)
    if duchies
      duchies.each do |duchy|
        # create duke / duchess
        ruler = create_adult duchy.kingdom, "male"
        Title.make_duke ruler, duchy
        # make duke / duchess vassal of kingdom ruler
        Relation.vassalize ruler, duchy.kingdom.ruler
        # create spouse for duchy ruler
        create_spouse ruler
        # create court officials
        create_court_officials ruler, duchy.kingdom
        
        # create bishop
        priest = create_adult duchy.kingdom, "male", "Ecclesiastical"
        Title.make_bishop priest, duchy
        Relation.vassalize priest, ruler
      end
    end
  end
  
  def populate_counties
    counties = County.find(:all)
    if counties
      counties.each do |county|
        # create count / countess
        ruler = create_adult county.duchy.kingdom, "male"
        Title.make_count ruler, county
        # make count / countess vassal of duchy
        Relation.vassalize ruler, county.duchy.ruler
        
        # create spouse for county ruler
        create_spouse ruler, county.duchy.kingdom
        # create court officials
        create_court_officials ruler, county.duchy.kingdom
        
      end
    end
  end
  
  def populate_towns
    towns = Town.find(:all)
    if towns
      towns.each do |town|
        # create earl / countess
        ruler = create_adult town.county.duchy.kingdom, "male"
        Title.make_earl ruler, town
        # make earl / countess vassal of county
        Relation.vassalize ruler, town.county.ruler
        
        # create spouse for town ruler
        create_spouse ruler, town.county.duchy.kingdom
        # create court officials
        create_court_officials ruler, town.county.duchy.kingdom
          
        # create dean
        priest = create_adult town.county.duchy.kingdom, "male", "Ecclesiastical"
        Title.make_dean priest, town
        Relation.vassalize priest, ruler
       
      end
    end
  end
  
  def give_children
    # give married men some children
    fathers = Character.find_all_by_marital_status_and_sex("married", "male")
    if fathers
      fathers.each do |father|
        # create 2 - 8 children ages 0 - (character.age - 20)
        total = rand(6) + 2
        x = 0
        while x < total do
          create_child father
          x = x + 1
        end
      end
    end
  end
  
  def give_spouses
    # give single men over age of 20 a spouse unless they are in the clergy
    men = Character.find_all_by_marital_status_and_sex("single", "male")
    if men
      men.each do |man|
        create_spouse (man) unless man.clergy? or man.age < 20
      end
    end
  end
end
